﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EBA.Framework;
using EBA.IoC;
using System.Diagnostics;
using System.Threading;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;
using System.Windows.Forms;

namespace EBA.Framework.BundleLauncher
{

    class Program
    {
        /// <summary>
        /// 参数列表：
        ///     (1)名称:name
        ///     (2)端口:port
        ///     (3)地址:address
        /// </summary>
        /// <param name="args"></param>
        [LoaderOptimization(LoaderOptimization.MultiDomainHost)]
        static void Main(string[] args)
        {

            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // Console.WriteLine(string.Join(",",args));
            //Debugger.Launch();
            var runtime = args[0];
            var bundleId = args[1];
            var bundleType = args[2];
            var bundleAssembly = args[3];



            AppDomain.CurrentDomain.Load(bundleAssembly);


            var factory = new RemotingBundleFactory();

            RemotingBundle = factory.CreateRemotingBundle(Type.GetType(bundleType), runtime, bundleId);

            AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit;


            SyncEvent = new AutoResetEvent(false);
            SyncEvent.WaitOne();

        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Application.Exit();
        }

        static IDisposable RemotingBundle { get; set; }

        static void CurrentDomain_ProcessExit(object sender, EventArgs e)
        {
            RemotingBundle.Dispose();
            RemotingBundle = null;
            SyncEvent.Set();
        }

        static AutoResetEvent SyncEvent { get; set; }
    }
}
